<?php
/**
 * @title 102. 二叉树的层序遍历 - 迭代
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param TreeNode $root
     * @return Integer[][]
     */
    function levelOrder($root) {
        /**
         * @since 2020-08-13 特殊情况
         */
        if($root === null){
            return [];
        } else {}

        /**
         * @since 2020-08-13 结果集
         */
        $result = [];

        /**
         * @since 2020-08-13 迭代节点集合
         */
        $nodes = [$root];

        /**
         * @since 2020-08-13 迭代
         */
        while($nodes){
            $nextNodes = [];

            /**
             * @since 2020-08-13 遍历层
             */
            $levels = [];
            foreach ($nodes as $node){
                $levels[] = $node->val;

                /**
                 * @since 2020-08-13 左右节点
                 */
                $left = $node->left;
                if($left !== null){
                    $nextNodes[] = $left;
                } else {}

                $right = $node->right;
                if($right !== null){
                    $nextNodes[] = $right;
                } else {}
            }
            $result[] = $levels;

            /**
             * @since 2020-08-13 下次迭代
             */
            $nodes = $nextNodes;
        }

        /**
         * @return
         */
        return $result;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.13_2.php
 */
$datas = [
    [3,9,20,null,null,15,7],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->levelOrder($xhprof->tree($data));
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
